﻿using System;
using System.Text;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Diagnostics;
using MQTTnet.Protocol;
using MQTTnet.Server;

namespace MqttBased
{
    public class MqttServerProvider
    {
        private static MqttServer _mqttServer;

        public async Task CreateServiceInstance(MqttSettingConfig setting, Action<MqttServer> registerHandler)
        {
            if (await CreateServiceInstanceBase(setting))
            {
                registerHandler.Invoke(_mqttServer);
                Console.WriteLine("mqtt服务启动成功!");
            }
        }
        public async Task CreateServiceInstance(MqttSettingConfig setting)
        {
            if (await CreateServiceInstanceBase(setting))
            {
                _mqttServer.ApplicationMessageReceived += (s, e) =>
                {
                    Console.WriteLine($"客户端[{e.ClientId}]>> 主题：{e.ApplicationMessage.Topic} 负荷：{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)} Qos：{e.ApplicationMessage.QualityOfServiceLevel} 保留：{e.ApplicationMessage.Retain}");

                };
                _mqttServer.ClientConnected += (s, e) =>
                {
                    Console.WriteLine($"客户端[{e.ClientId}]已连接");
                };
                _mqttServer.ClientDisconnected += (s, e) =>
                {
                    Console.WriteLine($"客户端[{e.ClientId}]已断开连接！");

                };
                Console.WriteLine("mqtt服务启动成功!");
            }
        }

        public async Task CloseServer()
        {
            if (_mqttServer != null)
            {
                await _mqttServer.StopAsync();
            }
        }

        private async Task<bool> CreateServiceInstanceBase(MqttSettingConfig setting)
        {
            MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
            {
                Console.WriteLine($">> 线程ID：{e.TraceMessage.ThreadId} 来源：{e.TraceMessage.Source} 跟踪级别：{e.TraceMessage.Level} 消息: {e.TraceMessage.Message}");
                if (e.TraceMessage.Exception != null)
                {
                    Console.WriteLine(e.TraceMessage.Exception);
                }
            };
            if (_mqttServer == null)
            {
                try
                {
                    _mqttServer = new MqttFactory().CreateMqttServer() as MqttServer;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return false;
                }
                var optionsBuilder = new MqttServerOptionsBuilder()
                    .WithDefaultEndpointPort(setting.Port)
                    .WithConnectionValidator(x =>
                    {
                        //if (x.Username != setting.UserName || x.Password != setting.Password)
                        //{
                        //    x.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                        //}
                    });
                await _mqttServer.StartAsync(optionsBuilder.Build());
            }
            return true;
        }
    }
}
